package com.app.couponsharelife.ui.main.me.experiencemen

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import com.alipay.sdk.app.PayTask
import com.google.gson.Gson
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TYGWXPAYBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.ui.main.home.shopweb.TaoBaoWebActivity
import com.app.couponsharelife.utils.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_experiencepay.*
import kotlinx.android.synthetic.main.base_title_white.*
import okhttp3.MediaType
import okhttp3.RequestBody

/**
 *Created by xct on 2019/1/19
 *Description:体验官支付页面
 */
class ExperienceMenPayActivity:BaseActivity() {
    private var payType=0
    private val SDK_PAY_FLAG = 1
    private val SDK_AUTH_FLAG = 2
    private var intentType=""
    private var intentdata=""
    private var intentdata1=""
    private var buyType="0"
    private var orderNum=""
    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String, String>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.getResult()// 同步返回需要验证的信息
                    val resultStatus = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //Toast.makeText(OnlinePayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        ToastUtil.getInstance().showToast("支付成功!")
                        getOrderNum()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.getInstance().showToast("取消支付!")
                    }
                }
                else -> {

                }
            }
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.activity_experiencepay
    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        intentType=intent.getStringExtra("Type")?:""
        intentdata=intent.getStringExtra("Data")?:""
        intentdata1=intent.getStringExtra("Data1")?:"0"
        basetitle_llclose.setOnClickListener { finish() }
        basetitle_title.visibility=View.GONE
        experiencepay_llzfb.setOnClickListener {
            payType=0
            experiencepay_imgzfb.setImageResource(R.drawable.imag_duihao_red)
            experiencepay_imgwx.setImageResource(R.drawable.shape_huan_gray97)
        }
        experiencepay_llwx.setOnClickListener {
            payType=1
            experiencepay_imgwx.setImageResource(R.drawable.imag_duihao_red)
            experiencepay_imgzfb.setImageResource(R.drawable.shape_huan_gray97)
        }
        experiencepay_but.setOnClickListener {
            if (0==payType){
                getZFBPayData()
            }else{
                getWXPayData()
            }
        }
        when(intentType){
            "CEO"->{  //首席
                buyType="0"
                experiencepay_but.text="立即支付 ¥1987.00"
            }
            "Curriculum"->{  //合伙人
                buyType="1"
                experiencepay_but.text="立即支付 ¥8400.00"
            }
            else->{
                buyType="0"
                experiencepay_but.text="立即支付 ¥1987.00"
            }
        }
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("wechatrepay"))])
    fun receiveData(fresh: String) {
        getOrderNum()
    }
    private fun startIntent(){
        if ("Curriculum"==intentType){  //合伙人
            var intent:Intent?=null
            if ("0"==intentdata1){
                intent=Intent(this, ExperienceCurriculumActivity::class.java)
            }else{
                intent=Intent(this, MainActivity::class.java)
                intent.putExtra("Type","ExperienceMen")
                intent.putExtra("Status",intentType)
            }
            startActivity(intent)
            finish()
        }else{
            /*val intent=Intent(this, MainActivity::class.java)
            intent.putExtra("Type","ExperienceMen")
            intent.putExtra("Status",intentType)
            startActivity(intent)*/
            if (orderNum.isEmpty()){
                showToastMsg("订单号错误，请稍后再试！")
                return
            }
            //openTime=201904041512288976&userid=311
            AppUtils.setString("SXPay","true")
            val url="http://www.yiyepay.cn/buyMember/address.html?openTime=${System.currentTimeMillis()}&userId=${AppUtils.getString(Contacts.USERID,"")}&isShowAlert=false&orderNum=$orderNum"
            intent = Intent(this, TaoBaoWebActivity::class.java)
            intent.putExtra("url", url)
            intent.putExtra("source", "ExperienceMenPay")
            intent.putExtra("name", "完善收货地址")
            startActivity(intent)
            finish()
        }
    }
    private fun getZFBPayData(){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["sellerid"]=AppUtils.getString(Contacts.USERID,"")
        map["type"]=buyType
        map["updown"]=intentdata
        RetrofitWorker.retrofitWorker.getZFBTYGPay(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            val payRunnable = Runnable {
                                val alipay = PayTask(this@ExperienceMenPayActivity)
                                val result = alipay.payV2(it.data!!, true)
                                val msg = Message()
                                msg.what = SDK_PAY_FLAG
                                msg.obj = result
                                mHandler.sendMessage(msg)
                            }

                            val payThread = Thread(payRunnable)
                            payThread.start()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getWXPayData(){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["type"]=buyType
        map["updown"]=intentdata
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.getWXTYGPay(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<TYGWXPAYBean>>(){
                    override fun onComplete() {

                    }
                    override fun onNext(it: RemoteResultBean<TYGWXPAYBean>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            PayUtil().wechatPay(this@ExperienceMenPayActivity,
                                    it.data!!.appid,
                                    it.data!!.partnerid,
                                    it.data!!.prepayid,
                                    it.data!!.noncestr,
                                    it.data!!.timestamp,
                                    it.data!!.`package`,
                                    it.data!!.sign)
                        }
                    }
                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                    }
                })
    }
    private fun getOrderNum(){
        showProgressDialog("加载中...")
        val map=HashMap<String,String>()
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getSXOrderNum(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            orderNum=it.data?:""
                            startIntent()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        showToastMsg("加载出错！")
                    }
                })
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}